package cn.heygod.airsql.util;

import cn.heygod.airsql.exception.AirSqlException;

import java.lang.reflect.Method;

/**
 * @className: ClassUtil
 * @author: Simon
 * @description: TODO
 * @date: 2024/1/27 2:25
 * @version: 1.0
 */
public class ClassUtil {

    public static Method getMethod(String className,String methodName){
        try {
            Class cls = forName(className);
            return cls.getMethod(methodName);
        } catch (NoSuchMethodException e) {
            throw new AirSqlException(e);
        }
    }

    public static <T> T getMethodAnnotation(String className,String methodName,Class annotationClass){
        try {
            Class cls = forName(className);
            return (T)cls.getMethod(methodName).getAnnotation(annotationClass);
        } catch (NoSuchMethodException e) {
            throw new AirSqlException(e);
        }
    }

    public static <T> T getDeclaredFieldAnnotation(String className,String fieldName,Class annotationClass){
        try {
            Class cls = forName(className);
            return (T)cls.getDeclaredField(fieldName).getAnnotation(annotationClass);
        } catch (NoSuchFieldException e) {
            throw new AirSqlException(e);
        }
    }

    private static Class forName(String className){
        String name = className.replaceAll("/",".");
        try {
            return Class.forName(name);
        } catch (ClassNotFoundException e) {
            throw new AirSqlException(e);
        }

    }
}
